using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Excel.Dao;
using T.FAS.Runtime.Excel.Entity;
using T.FAS.Runtime.Metadata.Entity.DataModel;
using T.FAS.Runtime.Metadata.Client;
using AppContext = T.ServiceComponent.Session.Service.AppContext;

namespace T.FAS.Runtime.Excel.Service
{
    public class ImportTaskManager
    {
        readonly ImportTaskLogic importTaskLogic = new ImportTaskLogic();
        readonly ImportExecutor importExecutor = new ImportExecutor();
        /// <summary>
        /// 导入确认
        /// </summary>
        /// <param name = "fileURL"></param>
        public Dictionary<string, object> ImportConfirm(string fileURL, bool isEnableExplainRow, List<ImportDef> importDefs)
        {
            return importExecutor.ImportConfirm(fileURL, isEnableExplainRow, importDefs);
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name = "importParam"></param>
        /// <param name = "importDefs"></param>
        public ImportTask ImportData(ImportParam importParam, List<ImportDef> importDefs, List<ImportVariable> importVariables)
        {
            return importExecutor.ImportData(importParam, importDefs, importVariables);
        }
        /// <summary>
        /// 失败重试
        /// </summary>
        /// <param name = "importTaskDetail"></param>
        /// <param name = "importDefs"></param>
        /// <returns></returns>
        public ImportTask Retry(string taskID, ImportParam importParam, List<ImportDef> importDefs, List<ImportVariable> importVariable)
        {
            importParam.TaskID = taskID;
            return importExecutor.ImportData(importParam, importDefs, importVariable);
        }

        /// <summary>
        /// 下载导入模板
        /// </summary>
        /// <param name = "cdoID"></param>
        /// <param name = "importDefs"></param>
        /// <returns></returns>
        public Dictionary<string, string> DownloadTemplate(string cdoID, bool isEnableExplainRow, bool isEnableUniqueCol, List<ImportDef> importDefs)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            CompositeDataObject cdo = MetaDataClientService.GetInstance().GetMetaDataContent(cdoID) as CompositeDataObject;
            if (cdo == null)
                throw new FasException(ExcelConstCode.ExportFailed, $"{T.ServiceComponent.I18N.Service.TermService.Current.GetText("T_FAS_fasr_Excel_1966905149", "获取CDO元数据失败:")}" + cdoID);
            try
            {
                ImportParam importParam = new ImportParam { CDOID = cdoID, IsEnableExplainRow = isEnableExplainRow, IsEnableUniqueCol = isEnableUniqueCol };
                byte[] byteContent = importExecutor.GetTemplate(importParam, cdo, importDefs);
                dic["fileName"] = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}.{FileUtil.DefaultExcel}";
                dic["state"] = "1";
                dic["content"] = FileUtil.GetBase64Type(FileUtil.DefaultExcel) + Convert.ToBase64String(byteContent);
            }
            catch (Exception e)
            {
                dic["state"] = "0";
                dic["errmsg"] = e.Message;
            }

            return dic;
        }

        /// <summary>
        /// 查询导入任务列表
        /// </summary>
        /// <param name = "cdoID"></param>
        /// <param name = "filter"></param>
        /// <returns></returns>
        public Dictionary<string, object> GetImportTaskList(string cdoID, Dictionary<string, string> filter)
        {
            return importTaskLogic.GetTaskList(cdoID, filter);
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name = "taskID"></param>
        /// <returns></returns>
        public Dictionary<string, string> DeleteImportTask(string taskID)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            try
            {
                ImportTask importTask = importTaskLogic.GetTask(taskID);
                if (importTask == null)
                {
                    dic.Add("state", "1");
                    return dic;
                }
                importTaskLogic.DeleteTask(taskID);
                List<Resource> resources = new List<Resource>();
                resources.Add(new Resource{RelativeUrl = importTask.FileURL});
                FileUtil.DelResult(resources);
                dic.Add("state", "1");
            }
            catch (Exception e)
            {
                dic.Add("state", "0");
                dic.Add("errmsg", e.Message);
            }

            return dic;
        }

        /// <summary>
        /// 清空任务
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, string> ClearImportTask(string cdoID)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            try
            {
                List<ImportTask> importTasks = importTaskLogic.GetTaskList(cdoID);
                importTaskLogic.ClearTask(cdoID);
                List<Resource> resources = new List<Resource>();
                foreach (var item in importTasks)
                {
                    resources.Add(new Resource{RelativeUrl = item.FileURL});
                }

                FileUtil.DelResult(resources);
                dic.Add("state", "1");
            }
            catch (Exception e)
            {
                dic.Add("state", "0");
                dic.Add("errmsg", e.Message);
            }

            return dic;
        }

        /// <summary>
        /// 清空任务
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, string> CleanTask(int days)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            ExportTaskLogic exportTaskLogic = new ExportTaskLogic();
            try
            {
                DateTime dateTime = DateTime.Now.AddDays(days);
                List<ImportTask> importTasks = importTaskLogic.GetOutofdateTaskList(dateTime);
                List<Resource> resources = new List<Resource>();
                foreach (var item in importTasks)
                {
                    importTaskLogic.DeleteTask(item.ID);
                    resources.Add(new Resource{RelativeUrl = item.FileURL});
                }

                List<ExportTask> exportTasks = exportTaskLogic.GetOutofdateTaskList(dateTime);
                foreach (var item in exportTasks)
                {
                    exportTaskLogic.DeleteTask(item.ID);
                    resources.Add(new Resource{RelativeUrl = item.FileURL});
                }

                FileUtil.DelResult(resources);
                dic.Add("state", "1");
            }
            catch (Exception e)
            {
                dic.Add("state", "0");
                dic.Add("errmsg", e.Message);
            }

            return dic;
        }

        /// <summary>
        /// 查询导入任务明细
        /// </summary>
        /// <param name = "taskID"></param>
        /// <returns></returns>
        public Dictionary<string, object> GetImportTaskDetailList(string taskID, Dictionary<string, string> filter)
        {
            return importTaskLogic.GetTaskDetailList(taskID, filter);
        }
    }
}